{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "        bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "        bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "        encoder_state = tuple([bi_lstm_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[20977, 20977, 20977, 20977, 20977, 20977, 29424, 29424, 29424,\n",
       "         29424, 29424, 29424, 29424, 29424, 29424, 29424, 29424, 29424,\n",
       "         29424, 29424, 29424, 29424, 29424, 29424, 29424, 29424, 20993,\n",
       "         20993, 20993, 20993, 27360, 27360, 27360,  1596,  1596,   673,\n",
       "           673,  8445,  8445,   621,   621, 30890, 30890, 30890, 30890,\n",
       "         30305, 30305, 30305, 30305, 30305, 30305, 21659, 21659, 21659,\n",
       "         21659, 21659, 26107,  8298, 21312, 21312, 21312, 21312, 21312,\n",
       "         21312, 27572, 27572, 27572, 27572, 27572, 27572,   806,  4463],\n",
       "        [20373, 20373, 15161, 14749, 14749, 14749, 14749, 14749, 14749,\n",
       "         11060, 11060, 25364, 25364, 12627, 12627, 12627, 12627,  3887,\n",
       "          3887,  3887,  3887,  3887,  8114, 26873, 26873, 26873, 26873,\n",
       "         26873, 26873, 26873, 26873, 26873, 31653,  3531,  3531,  3531,\n",
       "          3531,  8713,  8713,  8713,  8713,  8713, 26556, 26556, 27935,\n",
       "         27935, 27935, 27935, 27477, 22346, 22346, 22346, 21570, 21570,\n",
       "         21570, 21570, 23050, 23050,  8667,  8667,  8667,  8667, 12231,\n",
       "         12231, 12231, 12231, 12231, 15382, 15382, 15382, 15382, 20699],\n",
       "        [10479, 10479, 25875, 16847, 16847, 16847, 14016, 14016, 14016,\n",
       "         14016, 14016, 22190, 22190, 22190, 22190, 22190, 22190, 17210,\n",
       "         17210, 17210, 12383, 12383, 12383, 12383, 12383, 24544, 24544,\n",
       "         24544, 24544, 31683, 31683, 31683, 31683, 31683, 16246, 31683,\n",
       "         31683, 16246, 31683, 31683, 16246, 16246, 31683, 12663, 12663,\n",
       "         31683,  8077,  8077,  8077,  8077,  8077, 29973, 29973, 29973,\n",
       "         17318, 31915, 31915, 31915, 31915, 31915, 31915, 16743, 16743,\n",
       "         16743, 16743, 16743, 16743, 27717, 27717, 27717, 27717, 27717],\n",
       "        [24803, 24803, 18243,  8198,  8198,  8198, 21840,  8198, 21840,\n",
       "         21840, 21840, 29434, 29434, 29434, 29434, 26054, 26054, 26054,\n",
       "         26054, 26054,  4964,  4964,  4964,  4964, 25911, 25911,  2960,\n",
       "          2960,  2960,  2960,  2960,  2960,  2960,  2960,  9320,  9320,\n",
       "          8425,  8425,  8425,  8425,  8425,  8425,  8425, 26646,    82,\n",
       "            82,    82,    82,  8425,  8425,  8425,  8425,  8425, 26646,\n",
       "         26646, 26646, 26646,    82, 16478,    82,    82,    82, 10095,\n",
       "         10095, 10095, 31326, 31326, 31326, 17031, 17031, 17031, 17031],\n",
       "        [22956,  1386,  1386,  1386,  1386, 14434,  8003,  8003,  8003,\n",
       "          8003, 24330, 24330, 28180,  6248, 28180, 28180, 28180,  2339,\n",
       "          2339,  7253,  7253,  7253,  1269,  1269,  1269, 17645, 23568,\n",
       "         23568, 23568, 23568, 23568, 23568, 17016, 17016,  1932, 17016,\n",
       "         17016,  6392,  6392,  6392,  6392,  6392,  6392,  6392,  6392,\n",
       "          6392,  6392,  6392,  6392,  6392,  6392,  6392,  6392,  6392,\n",
       "          6392,  6392,  6392,  6392,  6392,  6392,  6392,  6392,  6392,\n",
       "          6392,  6392,  6392,  6392,  6392,  6392,  6392,  6392,  6392],\n",
       "        [15938, 15938, 15938, 26740, 22984, 22984, 22984, 22984, 22984,\n",
       "         22984, 22984,  9891, 28343, 28343, 28343, 28343, 28343, 28343,\n",
       "         28343, 28343, 20191, 20191, 20191, 20191, 20191, 29948, 29948,\n",
       "          1776, 28231, 28231, 28231, 28231, 28231, 28231, 27518,  8752,\n",
       "          8752,  8752, 12160, 12160, 12160, 12160, 12160, 12160, 31127,\n",
       "         31127, 31127, 27126, 27126, 27126, 27126, 27126, 27126, 10049,\n",
       "          7644,  7644,  7644,  7644,  7644,  7644,  3893,  3893, 27039,\n",
       "         27039, 27039, 27039, 12160, 12160, 12160, 12160, 25077, 25077],\n",
       "        [ 4142,  4142,  4142,  4142,  4142,  4142,  7214,  7214, 20148,\n",
       "         20148, 12004, 12004, 12004, 10655, 10655,   613,   613,   613,\n",
       "           613,   613,  9258,  9258, 20428, 20428, 20428, 20428,  9811,\n",
       "          9811,   700,   700,   700,   700,   700,   700,   700, 19765,\n",
       "         19765, 19765, 19765, 17763, 17763, 17763, 17763, 17763,  5897,\n",
       "          5897,  9063,  9063,  9063, 18912, 18912, 18912, 18912, 21053,\n",
       "         21053, 13047, 13047,  2896,  2896,  2896,  2896, 11783,  4898,\n",
       "         29767, 29767,  4898,  4898, 25309, 25309, 25309, 25309, 25309],\n",
       "        [ 3024,  3024,  3024,  3024,  3024,  3024, 26412, 26412, 26412,\n",
       "         26412, 26412, 26412, 26412, 26412, 12840, 12840, 10354, 12840,\n",
       "         15087, 15087, 15087, 15087, 15087, 30821, 30821, 30821, 30821,\n",
       "         15087, 29395, 29395, 29395, 29395, 15087, 15087, 15087, 15087,\n",
       "         13810, 13810,  3024,  3024,  3024,  3024,  3024, 26113, 26113,\n",
       "           748,   748,   748, 12942, 12942, 12942, 12942, 12942, 31687,\n",
       "         31687, 31687, 31687, 31687,    53,    53,    53,    53,    53,\n",
       "         10520, 10520, 10520, 22954,  8840,  8840,  8840,  8840,  8840],\n",
       "        [ 8274, 22730, 22730, 22730, 31636, 29243, 29243, 29243, 29243,\n",
       "         29243, 29243, 29243, 29243,  2787, 30159, 30159, 30159, 30159,\n",
       "         30159, 30159, 30159, 30159, 27853, 27853, 27853, 27853, 27853,\n",
       "         27853, 27853, 27853, 27853, 27853, 27853,  9257,  9257,  9257,\n",
       "         31554, 31554, 31554, 25836, 25836, 25836, 25836, 25836, 25836,\n",
       "         25836, 21844, 21844, 21844,  9903,  9903,  9903,  9903,  8274,\n",
       "         17397, 17397, 17397,  8559,  1260,  1260,  1260,  1260,  1260,\n",
       "          1260,  1260,  1260,  1260,  1260,  1260,  1260, 30254, 30254],\n",
       "        [31238,  1922,  1922, 26420, 12383, 12383, 31799, 31799, 31799,\n",
       "         31799, 31799,  1526, 17804, 17804,  1526,  1526, 17804,  1526,\n",
       "          1526,  1526,    25,  2122,  2122,  2122,  2122, 23907, 23907,\n",
       "         23907, 26752, 26752, 20165, 20165, 20165, 20165, 20165, 20165,\n",
       "          2626,  2626,  2626,  2626,  2626,  2626,  2626, 11814, 11814,\n",
       "         11814, 11814, 11814, 14991, 12274, 12274, 12274, 12274, 29617,\n",
       "          5510,  5510,  5510,  5510,  3630,  3630,  3630, 21651, 21651,\n",
       "         21651, 21651, 19695, 19695, 11340, 11340, 21651,  5288, 12325]],\n",
       "       dtype=int32), 10.372833, 0.0]"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:51<00:00,  1.88it/s, accuracy=0.374, cost=3.87]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.83it/s, accuracy=0.43, cost=3.42] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.080915, training avg acc 0.252277\n",
      "epoch 1, testing avg loss 3.738409, testing avg acc 0.388361\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.488, cost=2.84]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.522, cost=2.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.234724, training avg acc 0.442169\n",
      "epoch 2, testing avg loss 2.970064, testing avg acc 0.477438\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:55<00:00,  1.87it/s, accuracy=0.563, cost=2.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.94it/s, accuracy=0.57, cost=2.35] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.634903, training avg acc 0.512335\n",
      "epoch 3, testing avg loss 2.696690, testing avg acc 0.511730\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.6, cost=1.98]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.559, cost=2.44]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.297643, training avg acc 0.554293\n",
      "epoch 4, testing avg loss 2.593322, testing avg acc 0.524957\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.659, cost=1.68]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.591, cost=2.25]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.059582, training avg acc 0.585765\n",
      "epoch 5, testing avg loss 2.538182, testing avg acc 0.534115\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.686, cost=1.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.94it/s, accuracy=0.618, cost=2.1] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.875844, training avg acc 0.611289\n",
      "epoch 6, testing avg loss 2.547741, testing avg acc 0.539524\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.709, cost=1.29]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.602, cost=2.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.722508, training avg acc 0.633907\n",
      "epoch 7, testing avg loss 2.583568, testing avg acc 0.538193\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.742, cost=1.14]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.95it/s, accuracy=0.624, cost=2.18]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.587722, training avg acc 0.654603\n",
      "epoch 8, testing avg loss 2.626764, testing avg acc 0.537242\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.758, cost=1.04]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.613, cost=2.31]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.474056, training avg acc 0.672620\n",
      "epoch 9, testing avg loss 2.678997, testing avg acc 0.535959\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:53<00:00,  1.87it/s, accuracy=0.788, cost=0.914]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.94it/s, accuracy=0.624, cost=2.29]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.367233, training avg acc 0.690368\n",
      "epoch 10, testing avg loss 2.742449, testing avg acc 0.535768\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.799, cost=0.815]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.94it/s, accuracy=0.608, cost=2.41]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.269824, training avg acc 0.707093\n",
      "epoch 11, testing avg loss 2.835622, testing avg acc 0.531762\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:53<00:00,  1.87it/s, accuracy=0.824, cost=0.748]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.586, cost=2.47]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.187687, training avg acc 0.721490\n",
      "epoch 12, testing avg loss 2.925889, testing avg acc 0.528095\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.84, cost=0.663] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.94it/s, accuracy=0.608, cost=2.46]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.115012, training avg acc 0.734347\n",
      "epoch 13, testing avg loss 3.013492, testing avg acc 0.526554\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.856, cost=0.611]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.94it/s, accuracy=0.591, cost=2.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.052833, training avg acc 0.745441\n",
      "epoch 14, testing avg loss 3.109735, testing avg acc 0.520602\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:54<00:00,  1.87it/s, accuracy=0.845, cost=0.621]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.94it/s, accuracy=0.602, cost=2.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.993297, training avg acc 0.756771\n",
      "epoch 15, testing avg loss 3.185958, testing avg acc 0.517897\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:41<00:00,  1.90it/s, accuracy=0.877, cost=0.518]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.05it/s, accuracy=0.591, cost=2.54]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.944921, training avg acc 0.765507\n",
      "epoch 16, testing avg loss 3.250135, testing avg acc 0.518573\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:20<00:00,  1.95it/s, accuracy=0.872, cost=0.501]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.05it/s, accuracy=0.591, cost=2.66]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.895371, training avg acc 0.775053\n",
      "epoch 17, testing avg loss 3.342790, testing avg acc 0.516404\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:19<00:00,  1.96it/s, accuracy=0.875, cost=0.467]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.07it/s, accuracy=0.586, cost=2.66]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.849976, training avg acc 0.784102\n",
      "epoch 18, testing avg loss 3.430784, testing avg acc 0.513427\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:20<00:00,  1.95it/s, accuracy=0.888, cost=0.424]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.11it/s, accuracy=0.586, cost=2.89]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.811247, training avg acc 0.791422\n",
      "epoch 19, testing avg loss 3.526128, testing avg acc 0.509686\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:22<00:00,  1.95it/s, accuracy=0.896, cost=0.388]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.12it/s, accuracy=0.565, cost=2.87]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.775182, training avg acc 0.798921\n",
      "epoch 20, testing avg loss 3.585000, testing avg acc 0.507427\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:28<00:00,  1.38it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.20042004"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
